﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

// 摇杆
public class Joystick
{
    // 外层大圈
    private Image _outImage;
    // 里层小圈
    private Image _innerImage;

    // 大圈半径
    private float _radius;

    // 摇杆向外界传递的信息
    public Action<Vector2> OnMove;
    public Action OnMoveStop;

    // 加载界面
    public void Init()
    {
        var uiRoot = UIManager.Instance.AddUI("Prefabs/UI/FightUI/Joystick", UILayer.FightUI);

        _outImage = uiRoot.FindComponent<Image>("Out");
        _radius = _outImage.rectTransform.rect.width * 0.5f;

        _innerImage = _outImage.gameObject.FindComponent<Image>("Inner");

        // 做拖动效果
        Touch touch = _outImage.gameObject.AddComponent<Touch>();

        touch.OnDragCallback = onDragOutBall;
        touch.OnPointerDownCallback = onDragBegin;
        touch.OnPointerUpCallback = onDragEnd;

        //var t = TimerMgr.Instance.CreateTimer(0.1f, -1, Loop);
        //t.Start();
    }

    private void onDragEnd(PointerEventData eventData)
    {
        // 小球归位
        Reset();

        if (OnMoveStop != null) { OnMoveStop(); }
    }

    private void onDragBegin(PointerEventData eventData)
    {
        onDragOutBall(eventData);
    }

    // 拖动大圈事件
    private void onDragOutBall(PointerEventData eventData)
    {
        Vector2 touchPos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(_outImage.rectTransform, eventData.position, eventData.pressEventCamera, out touchPos);
        var center = Vector2.zero;

        // 让当前的触摸坐标为小圈坐标
        _innerImage.transform.position = eventData.position;

        // 限制小圈移动范围
        Vector2 realPos;
        var touchVector = touchPos - center;
        if (touchVector.magnitude > _radius)
        {
            realPos = touchVector.normalized * _radius;
        }
        else
        {
            realPos = touchPos;
        }

        _innerImage.rectTransform.anchoredPosition = realPos;

    }

    public void Loop()
    {
        // 只有当摇杆有方向的时候，才执行移动
        var curVector = _innerImage.transform.position - _outImage.transform.position;
        if (curVector.magnitude < 0.01f)
        //if (curVector == Vector3.zero)
        {
            return;
        }

        if (OnMove != null) { OnMove(curVector.normalized); }
    }

    public void Reset()
    {
        _innerImage.transform.position = _outImage.transform.position;

    }
}
